<template>
  <a-card :bordered="false" class="card-area">
    <div :class="advanced ? 'search' : null">
      <!-- 搜索区域 -->
      <a-form layout="horizontal">
        <div :class="advanced ? null : 'fold'">
          <a-row>
            <a-col :md="12" :sm="24">
              <a-form-item
                label="编码"
                :labelCol="{ span: 5 }"
                :wrapperCol="{ span: 18, offset: 1 }"
              >
                <a-input v-model="queryParams.shopCode" />
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24">
              <a-form-item
                label="名称"
                :labelCol="{ span: 5 }"
                :wrapperCol="{ span: 18, offset: 1 }"
              >
                <a-input v-model="queryParams.shopName" />
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24">
              <a-form-item
                label="创建时间"
                :labelCol="{ span: 5 }"
                :wrapperCol="{ span: 18, offset: 1 }"
              >
                <range-date
                  @change="handleDateChange"
                  ref="createTime"
                ></range-date>
              </a-form-item>
            </a-col>
          </a-row>
        </div>
        <span style="float: right; margin-top: 3px;">
          <a-button type="primary" @click="search">查询</a-button>
          <a-button style="margin-left: 8px" @click="reset">重置</a-button>
        </span>
      </a-form>
    </div>
    <div>
      <div class="operator">
        <a-button
          type="primary"
          v-hasPermission="['shop:add']"
          @click="createShop"
          >新增</a-button
        >
        <a-button v-hasPermission="['shop:delete']" @click="batchDelete"
          >删除</a-button
        >
        <!-- :disabled="fileList.length === 1" -->
        <a-upload
          class="upload-area"
          :fileList="fileList"
          :remove="handleRemove"
          :beforeUpload="beforeUpload"
        >
          <a-button> <a-icon type="upload" /> 选择.xlsx文件 </a-button>
        </a-upload>
        <a-button
          @click="handleUpload"
          :disabled="fileList.length === 0"
          :loading="uploading"
        >
          {{ uploading ? '导入中' : '导入Excel' }}
        </a-button>
        <a-dropdown v-hasPermission="['shop:export']">
          <a-menu slot="overlay">
            <a-menu-item key="export-data" @click="exportExcel"
              >导出Excel</a-menu-item
            >
          </a-menu>
          <a-button> 更多操作 <a-icon type="down" /> </a-button>
        </a-dropdown>
      </div>
      <!-- 表格区域 -->
      <a-table
        ref="TableInfo"
        :columns="columns"
        rowKey="id"
        :dataSource="dataSource"
        :pagination="pagination"
        :loading="loading"
        :rowSelection="{
          selectedRowKeys: selectedRowKeys,
          onChange: onSelectChange
        }"
        @change="handleTableChange"
        :scroll="{ x: 1500 }"
      >
        <template v-if="text" slot="icon" slot-scope="text, record">
          <a-icon :type="text" />
        </template>
        <template slot="operation" slot-scope="text, record">
          <a-icon
            v-hasPermission="['shop:update']"
            type="setting"
            theme="twoTone"
            twoToneColor="#4a9ff5"
            @click="edit(record)"
            title="修改"
          ></a-icon>
          <a-badge
            v-hasNoPermission="['shop:update']"
            status="warning"
            text="无权限"
          ></a-badge>
        </template>
      </a-table>
    </div>
    <!-- 新增区域 -->
    <shop-add
      @close="handleShopAddClose"
      @success="handleShopAddSuccess"
      :shopAddVisiable="shopAddVisiable"
    >
    </shop-add>
    <!-- 修改区域 -->
    <shop-edit
      ref="shopEdit"
      @close="handleShopEditClose"
      @success="handleShopEditSuccess"
      :shopEditVisiable="shopEditVisiable"
    >
    </shop-edit>
  </a-card>
</template>

<script>
import RangeDate from '@/components/datetime/RangeDate'
import ShopAdd from './ShopAdd'
import ShopEdit from './ShopEdit'
export default {
  name: 'Shop',
  components: { RangeDate, ShopAdd, ShopEdit },
  data () {
    return {
      advanced: false,
      key: +new Date(),
      queryParams: {},
      dataSource: [],
      selectedRowKeys: [],
      pagination: {
        pageSizeOptions: ['10', '20', '30', '40', '100'],
        current: 1,
        pageSize: 10,
        defaultCurrent: 1,
        defaultPageSize: 10,
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal: (total, range) =>
          `显示 ${range[0]} ~ ${range[1]} 条记录，共 ${total} 条记录`
      },
      loading: false,
      shopAddVisiable: false,
      shopEditVisiable: false,
      fileList: [],
      uploading: false
    }
  },
  computed: {
    columns () {
      return [
        {
          title: '编码',
          dataIndex: 'shopCode',
          key: 'shopCode',
          width: 200,
          fixed: 'left'
        },
        {
          title: '名称',
          dataIndex: 'shopName',
          width: 200,
          align: 'center'
          // fixed: 'left'
        },
        {
          title: '片区',
          dataIndex: 'areaName',
          width: 200,
          align: 'center'
        },
        {
          title: '街道',
          dataIndex: 'street',
          width: 200,
          align: 'center'
        },
        {
          title: '具体地址',
          dataIndex: 'address',
          width: 200,
          align: 'center'
        },
        {
          title: '经营类型',
          dataIndex: 'opeType',
          width: 200,
          align: 'center'
        },
        {
          title: '操作',
          dataIndex: 'operation',
          width: 120,
          scopedSlots: { customRender: 'operation' },
          fixed: 'right'
        }
      ]
    }
  },
  mounted () {
    this.fetch()
  },
  methods: {
    onSelectChange (selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    handleShopEditClose () {
      this.shopEditVisiable = false
    },
    handleShopEditSuccess () {
      this.shopEditVisiable = false
      this.$message.success('修改商铺成功')
      this.fetch()
    },
    edit (record) {
      this.$refs.shopEdit.setFormValues(record)
      this.shopEditVisiable = true
    },
    handleShopAddClose () {
      this.shopAddVisiable = false
    },
    handleShopAddSuccess () {
      this.shopAddVisiable = false
      this.$message.success('新增商铺成功')
      this.fetch()
    },
    createShop () {
      this.shopAddVisiable = true
    },
    handleDateChange (value) {
      if (value) {
        this.queryParams.createTimeFrom = value[0]
        this.queryParams.createTimeTo = value[1]
      }
    },
    batchDelete () {
      if (!this.selectedRowKeys.length) {
        this.$message.warning('请选择需要删除的记录')
        return
      }
      let that = this
      this.$confirm({
        title: '确定删除所选中的记录?',
        content:
          '当您点击确定按钮后，这些记录将会被彻底删除，如果其包含子记录，也将一并删除！',
        centered: true,
        onOk () {
          let ids = that.selectedRowKeys.map((item, index) => {
            return that.dataSource[index].id
          })
          that
            .$delete('tShop', {
              shopIds: ids
            })
            .then(() => {
              that.$message.success('删除成功')
              that.selectedRowKeys = []
              that.fetch()
            })
        },
        onCancel () {
          that.selectedRowKeys = []
        }
      })
    },
    exportExcel () {
      this.$export('tShop/excel', {
        ...this.queryParams
      })
    },
    search () {
      this.fetch({
        ...this.queryParams
      })
    },
    reset () {
      // 取消选中
      this.selectedRowKeys = []
      // 重置分页
      this.$refs.TableInfo.pagination.current = this.pagination.defaultCurrent
      if (this.paginationInfo) {
        this.paginationInfo.current = this.pagination.defaultCurrent
        this.paginationInfo.pageSize = this.pagination.defaultPageSize
      }
      // 重置查询参数
      this.queryParams = {}
      // 清空时间选择
      this.$refs.createTime.reset()
      this.fetch()
    },
    handleTableChange (pagination, sorter) {
      // 将这三个参数赋值给Vue data，用于后续使用
      this.paginationInfo = pagination
      this.queryParams.pageSize = this.paginationInfo.pageSize
      this.queryParams.pageNum = this.paginationInfo.current
      // 将这两个个参数赋值给Vue data，用于后续使用
      this.fetch({
        ...this.queryParams
      })
    },
    fetch (params = {}) {
      if (this.paginationInfo) {
        // 如果分页信息不为空，则设置表格当前第几页，每页条数，并设置查询分页参数
        this.$refs.TableInfo.pagination.current = this.paginationInfo.current
        this.$refs.TableInfo.pagination.pageSize = this.paginationInfo.pageSize
        params.pageSize = this.paginationInfo.pageSize
        params.pageNum = this.paginationInfo.current
      } else {
        // 如果分页信息为空，则设置为默认值
        params.pageSize = this.pagination.defaultPageSize
        params.pageNum = this.pagination.defaultCurrent
      }
      this.loading = true
      this.$get('tShop', {
        ...params
      }).then(r => {
        let data = r.data
        this.loading = false
        this.dataSource = data.rows
        const pagination = { ...this.pagination }
        pagination.total = data.total
        this.pagination = pagination
      })
    },
    handleRemove (file) {
      if (this.uploading) {
        this.$message.warning('文件导入中，请勿删除')
        return
      }
      const index = this.fileList.indexOf(file)
      const newFileList = this.fileList.slice()
      newFileList.splice(index, 1)
      this.fileList = newFileList
    },
    beforeUpload (file) {
      this.fileList = [...this.fileList, file]
      return false
    },
    handleUpload () {
      const { fileList } = this
      const formData = new FormData()
      formData.append('file', fileList[0])
      this.uploading = true
      this.$upload('tShop/import', formData)
        .then(res => {
          let data = res.data
          if (data.code === '200') {
            this.$notification.success({
              message: '系统提示',
              description: data.message
            })
            this.fetch()
          } else if (data.code === '500') {
            let msg = data.data.map(element => {
              let message = element.errorFields.map(item => {
                return `${item.errorMessage}`
              })
              return `第${element.rowIndex}行 ${message.join(';')}`
            })
            this.$notification.error({
              message: '系统消息',
              duration: 5,
              description: `${msg.join(',')}:`
            })
          }
          this.uploading = false
        })
        .catch(r => {
          console.error(r)
          this.uploading = false
          this.fileList = []
          this.$notification.error({
            message: '错误提示',
            description: r && r.message
          })
        })
    }
  }
}
</script>
<style lang="less" scoped>
@import '../../../../static/less/Common';
</style>
